package com.hc.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Description：利用redis生成全局唯一id
 * @Author：曹杰克
 * @CreateTime：2022/10/29 9:49
 */
public class RedisIDWoker {
    private StringRedisTemplate stringRedisTemplate;
    //开始时间戳
    private static  final  long  BEGIN_TIMESTAMAP=1640995200L;
    //序列号的位数
    private static  final int Count_BITS = 32;

    /**
     * 传入商品种类或其他
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //1.1当前时间戳
        long timestamp =nowSecond-BEGIN_TIMESTAMAP;

        //2.生成序列号

        //2.1获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2 redis自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //3.拼接为64位并返回
        return timestamp<<Count_BITS | count;
    }

    public static void main(String[] args) {
        //获取时间
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        //获取当时秒数
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }
}
